<template>
<div class="editForm-wrapper">
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
     v-dialogDrag
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="99px" @submit.native.prevent>
      <el-row  :gutter="15">
        <el-col :span="50">
            <el-form-item label="姓名:" prop="name"
                :rules="[
                  {required: true, message:'姓名不能为空', trigger:'blur'},
                  {validator: validator.isName, trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写姓名" maxlength="20"  show-word-limit ></el-input>
           </el-form-item>
        </el-col>
        </el-row>
        <el-row  :gutter="15">
          <el-col :span="50">
              <el-form-item label="手机号:" prop="phone"
              :rules="[
                {required: true, message:'手机号不能为空', trigger:'blur'},
                {validator: validator.isMobile, trigger:'blur'},
                {validator:checkRepeatPhone, trigger:'blur'}
               ]">
                <el-input v-model="inputForm.phone" placeholder="请填写11位手机号"   maxlength="11" show-word-limit ></el-input>
             </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="15">
          <el-col :span="50">
              <el-form-item label="身份证号:" prop="idcard"
              :rules="[
                {required: true, message:'身份证号不能为空', trigger:'blur'},
                {validator: validator.isCardId, trigger:'blur'},
                {validator:checkRepeatisCard, trigger:'blur'}
               ]">
                <el-input v-model="inputForm.idcard" placeholder="请填写18位身份证号" maxlength="18" show-word-limit  ></el-input>
             </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="15">
          <el-col :span="50">
              <el-form-item label="资格证编号:" prop="credentNumber">
                <el-input v-model="inputForm.credentNumber" placeholder="请填写资格证编号"   maxlength="18" show-word-limit ></el-input>
             </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="15">
          <el-col :span="12" class="imageUploader">
            <el-form-item prop="idcardImagePath" label="上传身份证:">
              <el-upload
                class="avatar-uploader"
                :action="`${this.$http.BASE_URL}/truck/driver/idcardImageUpload`"
                :headers="{token: $cookie.get('token')}"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                 :show-file-list="false">
                <img v-if="inputForm.idcardImagePath" :src="inputForm.idcardImagePath" class="avatar">
                  <div v-if="inputForm.idcardImagePath"  class="delBut">
                      <img src="~@/assets/img/del.png" @click.stop="delImage('idcardImageId','idcardImagePath')" alt="" style="height:15px">
                  </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  :gutter="15">
          <el-col :span="12" class="imageUploader">
            <el-form-item prop="credentImagePath" label="驾驶证:">
              <el-upload
                class="avatar-uploader"
                :action="`${this.$http.BASE_URL}/truck/driver/credentImageUpload`"
                :headers="{token: $cookie.get('token')}"
                :on-success="credenthandleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                 :show-file-list="false">
                <img v-if="inputForm.credentImagePath" :src="inputForm.credentImagePath" class="avatar">
                  <div v-if="inputForm.credentImagePath"  class="delBut">
                      <img src="~@/assets/img/del.png" @click.stop="delImage('credentImageId','credentImagePath')" alt="" style="height:15px">
                  </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          name: '',
          phone: '',
          idcard: '',
          credentNumber: '',
          idcardImageId: '',
          credentImageId: '',
          idcardImagePath: '',
          credentImagePath: '',
          delImageIds: ''
        }
      }
    },
    components: {
    },
    methods: {
    	handleClose(done) {
			this.$Msg.confirm({
				title:'您确定要关闭吗？',
				content:this.GLOBAL.FORM_CLOSE_TIPS,
				confirmCall:()=>{
					done();
				}
			})
		},
        // 删除图片
        delImage(imgId,imgPath) {
          this.inputForm.delImageIds = this.inputForm.delImageIds + "," + this.inputForm[imgId]
          this.inputForm[imgPath] = ''
          this.inputForm[imgId] = ''
        },
      init (method, id) {
        this.method = method
        if (method === 'add') {
          this.title = `新增司机`
          this.inputForm.id = ""
        } else if (method === 'edit') {
          this.title = '修改司机'
          this.inputForm.id = id
        } else if (method === 'view') {
          this.title = '查看司机'
          this.inputForm.id = id
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/truck/driver/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              if (data.success) {
                this.inputForm = this.recover(this.inputForm, data.result)
                this.loading = false
              } else {
                this.loading = false
                this.visible = false
              }
            })
          }
        })
      },
      checkRepeatPhone(rule, value, callback){
        if (value) {
          this.$http({
            url: `/truck/driver/validate`,
            method: 'get',
            params: {'id': this.inputForm.id, 'phone': value}
          }).then(({data}) => {
            if (data.code !== '200') {
              callback(new Error(data.message))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      },
      checkRepeatisCard(rule, value, callback){
        if (value) {
          this.$http({
            url: `/truck/driver/validate`,
            method: 'get',
            params: {'id': this.inputForm.id, 'idcard': value}
          }).then(({data}) => {
            if (data.code !== '200') {
              callback(new Error(data.message))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      },
      // 文件上传成功后方法
      handleAvatarSuccess (res, file) {
        this.inputForm.delImageIds = this.inputForm.delImageIds + "," + this.inputForm.idcardImageId
        this.inputForm.idcardImageId = res.result.id
        this.inputForm.idcardImagePath = res.result.filePath
      },
      // 文件上传校验
      beforeAvatarUpload (file) {
        const isJPG = file.type.indexOf('image/') >= 0
        const isLt5M = file.size / 1024 / 1024 < 5

        if (!isJPG) {
          this.$message.error('上传只能是图片格式!')
          return false
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!')
          return false
        }
        return true
      },
      credenthandleAvatarSuccess (res, file) {
        this.inputForm.delImageIds = this.inputForm.delImageIds + "," + this.inputForm.credentImageId
        this.inputForm.credentImageId = res.result.id
        this.inputForm.credentImagePath = res.result.filePath
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/truck/driver/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              if (data && data.code === '200') {
                this.visible = false
                this.$message.success(data.message)
                this.$emit('refreshDataList')
              }
            })
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>

</style>
